<template>
  <div class="app-container">
    <div class="filter-container">
      <p style="float:left;margin-top:5px;margin-left:1%">服务中心名称：</p>
      <el-input
        v-model="listQuery.name"
        size="small"
        placeholder="请输入店铺名称"
        style="width: 200px;float:left"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <p style="float:left;margin-top:5px;margin-left:1%">代理人：</p>
      <el-input
        v-model="listQuery.agencyUserName"
        size="small"
        placeholder="请输入代理人"
        style="width: 200px;float:left"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <p style="float:left;margin-top:5px;margin-left:1%">代理人手机号：</p>
      <el-input
        v-model="listQuery.agencyUserPhone"
        size="small"
        placeholder="请输入手机号"
        style="width: 200px;float:left"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <p style="float:left;margin-top:5px;margin-left:1%">地址：</p>
      <el-cascader clearable :options="areaData" v-model="temp" size="small" ref="area" :props="{value: 'code', label: 'name'}" @change="areaChange" style="width:300px"></el-cascader>
      <el-button
        size="small"
        class="filter-item"
        type="success"
        icon="el-icon-search"
        style="margin-left:3%"
        @click="handleFilter"
      >
        搜索
      </el-button>
      <el-button
        size="small"
        class="filter-item"
        style="margin-left: 10px;float:right"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >添加</el-button>
    </div>

    <el-table
      :data="list"
      v-loading="listLoading"
      size="small"
      border
      fit
      highlight-current-row
      style="width: 100%;margin-top:1%"
    >
      <el-table-column type="index" label="序号" width="50px" align="center"></el-table-column>
      <el-table-column label="服务名称" min-width="150px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="代理人" width="100px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.agencyUserName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="代理人电话" width="100px" align="center">
        <template slot-scope="scope">
          <!-- <span>{{ scope.row.phoneNumber }}</span> -->
          <span>{{ scope.row.agencyUserPhone }}</span>
        </template>
      </el-table-column>
      <el-table-column label="地址" min-width="200px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.address }}</span>
        </template>
      </el-table-column>
      <el-table-column label="保证金额" width="100px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.ensureMoney }}</span>
        </template>
      </el-table-column>
      <el-table-column label="店铺状态" width="100px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.status==='USER_NOR_MAL'?'开启':'失效'}}</span>
        </template>
      </el-table-column>
      <el-table-column label="有效期" width="100px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.validityDate}}</span>
        </template>
      </el-table-column>
      <el-table-column label="店员数" width="50px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.saleAmount }}</span>
        </template>
      </el-table-column>
      <el-table-column label="乡镇代理人数" width="100px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.agencyTownAmount}}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="450px"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{ row }">
          <el-button
            size="small"
            align="center"
            type="primary"
            @click="handleUpdate(row)"
          >
            编辑
          </el-button>
          <el-button
            size="small"
            align="center"
            type="success"
            @click="handleDetails(row)"
          >
            查看
          </el-button>
          <el-button
            size="small"
            align="center"
            type="danger"
            @click="handleDel(row)"
          >
            删除
          </el-button>
          <el-button
            size="small"
            align="center"
            type="success"
            @click="handlSale(row)"
          >
            查看店员
          </el-button>
          <el-button
            size="small"
            align="center"
            type="primary"
            @click="handlTown(row)"
          >
            查看乡镇合伙人
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.pageNum"
      :limit.sync="listQuery.pageSize"
      @pagination="getList"
    />
    <el-dialog
      :close-on-click-modal="false"
      :title="textMap1[peopleStatus]"
      :visible.sync="peopleVisible"
      append-to-body
      @close='clearList'
      width="60%"
    >
      <el-table
      :data="dataList"
      size="small"
      border
      fit
      highlight-current-row
      style="width: 100%;margin-top:1%"
    >
      <el-table-column type="index" label="序号" width="50px" align="center"></el-table-column>
      <el-table-column label="店员姓名" min-width="150px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.nickName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="手机号" width="100px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.userName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="性别" width="100px" align="center">
        <template slot-scope="scope">
          <!-- <span>{{ scope.row.phoneNumber }}</span> -->
          <span>{{ scope.row.sex }}</span>
        </template>
      </el-table-column>
      <el-table-column label="年龄" min-width="100px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.year }}</span>
        </template>
      </el-table-column>
      <el-table-column label="身份证号" width="200px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.idCard }}</span>
        </template>
      </el-table-column>
      <el-table-column label="最后登陆时间" width="150px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.createTime }}</span>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="listTotal > 0"
      :total="listTotal"
      :page.sync="showQuery.pageNum"
      :limit.sync="showQuery.pageSize"
      @pagination="handleList"
    />
    <div slot="footer" class="dialog-footer">
        <el-button @click="peopleVisible = false">
          返回
        </el-button>
      </div>
    </el-dialog>
    <el-dialog
      :close-on-click-modal="false"
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      append-to-body
      width="60%"
      @closed='clearPage'
    >
      <el-form
        ref="dataForm"
        :model="temp"
        label-position="right"
        label-width="150px"
        :rules='rules'
        style="width: 650px; margin-left:150px;"
      >
        <el-form-item label="服务中心名称：" prop="name">
          <el-input v-model="temp.name" :disabled="dialogStatus == 'details' ? true : false"/>
        </el-form-item>
        <el-form-item label="代理人姓名：" prop="agencyUserName">
          <el-input v-model="temp.agencyUserName" :disabled="dialogStatus == 'details' ? true : false"/>
        </el-form-item>
        <el-form-item label="代理人电话：" prop="agencyUserPhone">
          <el-input v-model="temp.agencyUserPhone" :disabled="dialogStatus == 'details' ? true : false"/>
        </el-form-item>
        <el-form-item prop="idCard" label="代理人身份证号：">
          <el-input v-model="temp.idCard" :disabled="dialogStatus == 'details' ? true : false"/>
        </el-form-item>
        <el-form-item label="地址">
          <el-cascader clearable :options="areaData" v-model="adressList" size="small" ref="area" :props="{value: 'code', label: 'name'}" @change="areaChange" style="width:400px"></el-cascader>
        </el-form-item>
        <el-form-item label="店铺地址：" prop="address">
          <el-input v-model="temp.address" :disabled="dialogStatus == 'details' ? true : false"/>
        </el-form-item>
        <el-form-item label="保证金额：" prop="ensureMoney">
          <el-input v-model="temp.ensureMoney" :disabled="dialogStatus == 'details' ? true : false"/>
        </el-form-item>
        <el-form-item label="加盟费：" prop="initialMoney">
          <el-input v-model="temp.initialMoney" :disabled="dialogStatus == 'details' ? true : false"/>
        </el-form-item>
        <el-form-item label="有效期至：">
          <el-date-picker
           :disabled="dialogStatus == 'details' ? true : false"
            v-model="temp.validityDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="店铺状态：">
          <el-radio-group v-model="temp.status" :disabled="dialogStatus == 'details' ? true : false">
            <el-radio label="USER_NOR_MAL">开启</el-radio>
            <el-radio label="USER_EFFECT">失效</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- <el-form-item label="店铺图片：">
          <el-upload
            :disabled="dialogStatus == 'details' ? true : false"
            class="avatar-uploader"
            action="http://10.0.0.123:10001/uploadImgUrl"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :http-request="customRequest">
            <img style="width:100px;height:100px" v-if="temp.imgUrl" :src="temp.imgUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item> -->
        <el-form-item label="店铺商品标签：" prop="shopLabel">
          <el-input type="textarea" v-model="temp.shopLabel" :disabled="dialogStatus == 'details' ? true : false"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          返回
        </el-button>
        <el-button
          type="primary"
          @click="dialogStatus === 'create' ? createData('dataForm') : updateData()"
        >
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getListPage,addMechanism,updateMechanism,delData,getDetailsList } from '@/api/mechanism'
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // 分页插件
import {addImg} from '@/api/headWheel'
import areaData from "@/utils/area_data"
export default {
  inject:["reload"],
  components: { Pagination },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    },
  },
  data() {
    return {
      detailsVisible:false,
      deptValue:'',
      tableKey: 0,
      list: null,
      zhutiList:null,
      imgList:null,
      total: 0,
      listTotal:0,
      listLoading: false,
      dataList:[],
      showQuery:{
        pageNum: 1,
        pageSize: 10,
      },
      areaData: areaData,
      listQuery: {
        pageNum: 1,
        pageSize: 10,
        provinceCode: '',
        cityCode: '',
        countyCode: '',
        agencyUserName:'',
        agencyUserPhone:"",
        name:''
      },
      deps:[],
      info:'',
      rules: {
        name: [{ required: true, message: '店铺名称不能为空', trigger: 'blur' }],
        agencyUserName: [{ required: true, message: '代理人姓名不能为空', trigger: 'blur' }],
        agencyUserPhone: [{ required: true, message: '代理人电话不能为空', trigger: 'blur' }],
        idCard: [{ required: true, message: '代理人身份证号不能为空', trigger: 'blur' }],
        address: [{ required: true, message: '店铺地址不能为空', trigger: 'blur' }],
        ensureMoney: [{ required: true, message: '保证金额不能为空', trigger: 'blur' }],
        initialMoney:[{ required: true, message: '加盟费不能为空', trigger: 'blur' }],
        shopLabel:[{ required: true, message: '店铺标签不能为空', trigger: 'blur' }]
      },
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      temp: {
        countyCode:'',
        idCard:'',
        provinceCode:'',
        townCode:'',
        cityCode:''
      },
      adressList:[],
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '添加',
        details:'查看'
      },
      textMap1: {
        sale: '查看店员',
        town: '查看乡镇合伙人',
      },
      peopleStatus:"",
      peopleVisible:false,
      rowId:"",
    }
  },
  created() {
    this.getList()
  },
  methods: {
    //四级联动
    areaChange(value){
      this.temp.provinceCode=value[0]
      this.temp.cityCode=value[1]
      this.temp.countyCode=value[2]
      this.temp.townCode=value[3]
      var addressName=this.$refs['area'].getCheckedNodes()
      this.temp.province=addressName[0].pathLabels[0]
      this.temp.city=addressName[0].pathLabels[1]
      this.temp.county=addressName[0].pathLabels[2]
      this.temp.town=addressName[0].pathLabels[3]
      console.log(this.$refs['area'].getCheckedNodes())
    },
    //清除数据
    clearList(){
      this.listTotal = 0
      this.showQuery.pageNum=1
      this.showQuery.pageSize=10
    },
    clearPage(){
      this.adressList=[]
    },
    //店员
    handlSale(row){
      this.saleObj=row
      this.rowId=row.id
      this.peopleVisible=true
      this.peopleStatus='sale'
      var params={
        agencyId:this.rowId,
        userType:'COUNTY_SHOP_SALE'
      }
      var page={
        pageNum:this.showQuery.pageNum-1,
        pageSize:this.showQuery.pageSize
      }
      getDetailsList(params,page).then(res=>{
        this.dataList=res.data.content
        this.listTotal = res.data.totalElements
      })
    },
    //乡镇
    handlTown(row){
      this.townObj=row
      this.peopleVisible=true
      this.peopleStatus='town'
      this.rowId=row.id
      var params={
        agencyId:this.rowId,
        userType:'TOWN_AGENT'
      }
      var page={
        pageNum:this.showQuery.pageNum-1,
        pageSize:this.showQuery.pageSize
      }
      getDetailsList(params,page).then(res=>{
        this.dataList=res.data.content
        this.listTotal = res.data.totalElements
      })
    },
    // handleAvatarSuccess(res, file) {
    //     this.temp.imgUrl = URL.createObjectURL(file.raw);
    // },
    // customRequest (data) {
    //   const formData = new FormData()
    //   formData.append('file', data.file)
    //   this.saveFile(formData)
    // },
    // saveFile (formData) {
    //   addImg(formData).then(res=>{
    //     // this.imageUrl=res.data
    //     this.$set(this.temp, "imgUrl", res.data.filePath);
    //     console.log(this.temp.imgUrl)
    //   })
    // },
    filterStatus(status) {
      switch (status) {
        case "USER_EFFECT":
          return "失效";
        case "USER_NOR_MAL":
          return "开启";
        default:
          return "";
      }
    },
    getList() {
      var params = {
        provinceCode:this.temp.provinceCode,
        cityCode:this.temp.cityCode,
        countyCode:this.temp.countyCode,
        townCode:this.temp.townCode,
        name:this.listQuery.name,
      }
      var page={
        pageNum: this.listQuery.pageNum-1,
        pageSize: this.listQuery.pageSize,
      }
      getListPage(params,page).then(response => {
        this.list = response.data.content
        this.total = response.data.totalElements
        // Just to simulate the time of the request
      })
    },
    handleDel(row){
      this.rowId=row.id
      delData(this.rowId).then(res=>{
        if(res.code==='200'){
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          this.getList()
        }else{
          this.$notify({
            title: '失败',
            message: '删除失败',
            type: 'danger',
            duration: 2000
          })
        }
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleList() {
      if(this.peopleStatus==='sale'){
        this.handlSale(this.saleObj)
      }else if(this.peopleStatus==='town'){
        this.handlTown(this.townObj)
      }
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作成功',
        type: 'success'
      })
      row.status = status
    },
    resetTemp() {
      this.temp = {
      }
    },
    //编辑
     handleUpdate(row) {
      this.rowId=row.id
      var linshiList=[]
      linshiList.push(row.provinceCode,row.cityCode,row.countyCode,row.townCode)
      this.adressList=linshiList
      console.log(this.adressList)
      this.temp = Object.assign({}, row) // copy obj
      // this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    //查看详情
    handleDetails(row){
      this.rowId=row.id
      var linshiList=[]
      linshiList.push(row.provinceCode,row.cityCode,row.countyCode,row.townCode)
      this.adressList=linshiList
      this.temp = Object.assign({}, row) // copy obj
      // this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'details'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      delete this.temp['createTime']
      this.temp.initialMoney=Number(this.temp.initialMoney)
      this.temp.ensureMoney=Number(this.temp.ensureMoney)
      updateMechanism(this.temp).then(() => {
        this.listLoading=true
        this.dialogFormVisible = false
        this.$notify({
          title: '成功',
          message: '修改成功',
          type: 'success',
          duration: 4000
        })
        this.reload()
      })
    },
    //新增
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData(foName) {
      this.$refs[foName].validate((valid) => {
          if (valid) {
            addMechanism(this.temp).then(() => {
              this.list.unshift(this.temp)
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '添加成功',
                type: 'success',
                duration: 4000
              })
              this.reload()
            })
          } else {
            this.$notify({
              title: '失败',
              message: '所填项不能为空',
              type: 'danger',
              duration: 4000
            })
            return false;
          }
        });
      
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}`
        ? 'ascending'
        : sort === `-${key}`
          ? 'descending'
          : ''
    }
  }
}
</script>
<style scoped>
  .distpicker-address-wrapper select{
      height: 32px;
      padding: 0;
      font-size:14px;
  }
   /* /deep/ .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  } */
</style>